package com.example.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.annotations.*;

import com.example.auth.LoginUtils;
import com.example.auth.model.LoginLog;
import com.example.auth.model.UserModel;
import com.example.auth.service.LoginLogService;
import com.example.auth.service.UserModelService;
import com.example.auth.uitls.Md5Util;
import com.example.auth.uitls.TokenUtils;
import com.example.auth.uitls.UserModelMap;
import com.example.auth.uitls.UserModelUtils;
import com.example.db.model.IPage;
import com.example.utils.Results;
import com.example.utils.cacheutils.CacheUtils;

import java.util.Date;


/**
 * @Classname UserModelController
 * @Description TODO
 * @Date 2022/6/2 12:47
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController("/user")
public class UserModelController {

    @Autowired
    UserModelService userModelService;

    @Autowired
    LoginLogService loginLogService;

    @PostMapping(value = "/loginlogpage",desc = "用户登录日志")
    public JSONObject loginLogPageController(@Param(value = "pageNum",desc = "页码",defalultValue = "1")Integer pageNum,
                                             @Param(value = "pageSize",desc = "条数",defalultValue = "10")Integer pageSize,
                                             @Param(value = "searchParams",required = false)JSONObject object){
        IPage<LoginLog> loginLogIPage=loginLogService.page(pageNum,pageSize,object);
        return Results.successLayuiTable(loginLogIPage);

    }

    @GetMapping(value = "/removeonlineuser",desc = "用户下线")
    public JSONObject removeOnlineUserController(@Param("username")String username){
        userModelService.removeOnlineUserModelByUsername(username);
        return Results.success("下线成功");
    }

    @PostMapping(value = "/onlinepage",desc = "用户在线列表")
    public JSONObject userOnlineController(@Param(value = "pageNum",desc = "页码",defalultValue = "1")Integer pageNum,
                                           @Param(value = "pageSize",desc = "条数",defalultValue = "10")Integer pageSize,
                                           @Param(value = "searchParams",required = false)JSONObject object){
        IPage<UserModel> iPage=userModelService.getOnlineUserModel(pageNum,pageSize,object);
        return Results.successLayuiTable(iPage);
    }

    @GetMapping("/getuser")
    public JSONObject getUserController(@Param("username")String username){
        UserModel userModel=userModelService.getUserModel(username);
        return Results.success(userModel);
    }

    @GetMapping(value = "/getuserinfo",desc = "获取用户个人信息")
    public JSONObject getUserInfoController(){
        //此处获取的当前登录用户是缓存
        UserModel userModel=userModelService.getUserModel();
        //最新数据还得从数据库里面获取
        UserModel user=userModelService.getUserModelById(String.valueOf(userModel.getId()));
        user.setPassword("");
        return Results.success(user);
    }

    @PostMapping(value = "/updatepassword",desc = "密码修改")
    public JSONObject updatePasswordController(@Param(value = "password",desc = "新密码")String password,
                                               @Param(value = "oldpassword",desc = "旧密码")String oldpassword){
        //获取当前登录的用户
        UserModel userModel=userModelService.getUserModel();
        //获取用户最新数据
        //最新数据还得从数据库里面获取
        UserModel user=userModelService.getUserModelById(String.valueOf(userModel.getId()));
        String oldpass=Md5Util.strToMD5(oldpassword);
        if(!user.getPassword().equals(oldpass)){
            return Results.error("旧密码输入不正确");
        }
        String pass=Md5Util.strToMD5(password);
        user.setPassword(pass);
        userModelService.updateUserModelById(user);
        return Results.success("密码更新成功");
    }

    @GetMapping("/getuserbyid")
    public JSONObject getUserModelById(@Param("id")String uid){
        UserModel userModel=userModelService.getUserModelById(uid);
        if(userModel!=null){
            userModel.setPassword("");
        }
        return Results.success(userModel);
    }

    @PostMapping(value = "/updateuserbyid",desc = "更新用户")
    public JSONObject updateUserModelByIdController(@RequestBody UserModel userModel){
        if(userModel.getId()==null){
            return Results.error("用户id不得为空");
        }
        UserModel user=userModelService.getUserModelById(String.valueOf(userModel.getId()));
        if(user==null){
            return Results.error("用户信息不存在");
        }
        if(userModel.getPassword()!=null){
            String password = userModel.getPassword();
            password=Md5Util.strToMD5(password);
            userModel.setPassword(password);
        }
        //严禁更新账号
        userModel.setUsername(null);
        userModelService.updateUserModelById(userModel);
        return Results.success("用户信息更新成功");
    }

//    @GetMapping("/page")
//    public JSONObject getPageController(@Param("page")Integer page,
//                                        @Param("pageNum")Integer pageSize){
//        IPage<UserModel> iPage=userModelService.getUserModelPage(page,pageSize);
//        return Results.success(iPage);
//    }

    @PostMapping("/page")
    public JSONObject userModelPageController(@Param(value = "pageNum",desc = "页码",defalultValue = "1")Integer pageNum,
                                              @Param(value = "pageSize",desc = "条数",defalultValue = "10")Integer pageSize,
                                              @Param(value = "searchParams",required = false)JSONObject object){
        IPage<UserModel> iPage=userModelService.getUserModelPage(pageNum,pageSize,object);
        return Results.successLayuiTable(iPage);
    }

    @PostMapping("/saveuser")
    public JSONObject addSysUserModelController(@RequestBody UserModel userModel){
        if(userModel.getUsername()==null){
            return Results.error("账号不得为空");
        }
        UserModel user=userModelService.getUserModel(userModel.getUsername());
        if(user!=null){
            return Results.error("账号已存在");
        }
        if(userModel.getPassword()==null){
            return Results.error("密码不得为空");
        }
        String password=Md5Util.strToMD5(userModel.getPassword());
        userModel.setPassword(password);
        userModel.setIslocked(false);
        userModel.setCreatedate(new Date());
        userModelService.saveUserModel(userModel);
        return Results.success("新增成功");
    }



    @Auth
    @PostMapping(value = "/registeruser",desc = "用户注册")
    public JSONObject saveUserController(@Param(value = "username",desc = "用户名")String username,
                                         @Param(value = "password",desc = "密码")String password,
                                         @Param(value = "againpassword",desc = "确认密码")String againPassword){
        if(!password.equals(againPassword)){
            return Results.error("两次密码输入不一致");
        }
        UserModel userModel=userModelService.getUserModel(username);
        if(userModel!=null){
            return Results.error(username+"用户已存在");
        }
        userModel=new UserModel();
        userModel.setUsername(username);
        userModel.setCreatedate(new Date());
        String pass= Md5Util.strToMD5(againPassword);
        userModel.setPassword(pass);
        userModelService.saveUserModel(userModel);
        return Results.success("注册成功");
    }


    @Auth
    @PostMapping(value = "/login",desc = "登录")
    public JSONObject loginController(@Param(value = "username",desc = "用户名")String username,
                                      @Param(value = "password",desc = "密码")String password,
                                      @Param(value = "code",desc = "图片码")String code,
                                      @Param(value = "codeStr",desc = "图片文字")String codeStr){
        Object val=CacheUtils.get(code);
        if(val == null){
            return Results.error("验证码已过期");
        }
        String valStr=String.valueOf(val);
        if(!valStr.equals(codeStr)){
            return Results.error("验证码输入不正确");
        }
        UserModel userModel=userModelService.getUserModel(username);
        if(userModel==null){
            return Results.error("账号或密码错误");
        }
        LoginLog loginLog=new LoginLog();
        loginLog.setLoginDate(new Date());
        loginLog.setCreatedate(new Date());
        loginLog.setUserid(userModel.getId());
        loginLog.setRealname(userModel.getRealname());
        loginLog.setUsername(userModel.getUsername());
        String pass=Md5Util.strToMD5(password);
        System.out.println(pass);
        if(!userModel.getPassword().equals(pass)){
            loginLog.setStatus(1);
            loginLog.setMsg("账号或密码错误");
            loginLogService.save(loginLog);
            return Results.error("账号或密码错误");
        }
        loginLog.setStatus(0);
        loginLog.setMsg("登录成功");
        loginLogService.save(loginLog);
        String token= TokenUtils.getToken();
        UserModelMap.putUserModel(token,userModel);
        JSONObject obj=new JSONObject();
        obj.put("token",token);
        obj.put("username",username);
        obj.put("tip","登录成功");
        obj.put("code",200);
        return Results.success(obj);
    }

    @GetMapping(value = "/logout",desc = "退出登录")
    public JSONObject logoutController(){
        UserModel userModel=userModelService.getUserModel();
        if(userModel==null){
            return Results.error("用户已退出登录");
        }
        UserModelMap.removeTokenByUserName(userModel.getUsername());
        return Results.success("用户以安全退出");
    }

    @GetMapping(value = "/userIsExist",desc = "校验用户是否存在")
    public JSONObject userIsExistController(@Param("username")String username){
        UserModel userModel=userModelService.getUserModel(username);
        if(userModel!=null){
            return Results.error("用户已存在");
        }else {
            return Results.success("用户不存在");
        }
    }

    @Auth
    @GetMapping(value = "/islogin",desc = "获取用户是否登录")
    public JSONObject isLoginController(){
        UserModel userModel=userModelService.getUserModel();
        if(userModel==null){
            JSONObject obj = new JSONObject();
            obj.put("code",101);
            obj.put("isLogin",false);
            obj.put("tip","未登录");
            return Results.success(obj);
        }else {
            JSONObject obj = new JSONObject();
            obj.put("code",200);
            obj.put("isLogin",true);
            obj.put("tip","登录");
            obj.put("username",userModel.getUsername());
            return Results.success(obj);
        }
    }




}
